#include <string>
#include <ostream>
#include <istream>
#include <iostream>
#include <ios>
#include <fstream>
#include "../Headers/types.h"
#include "../Headers/authr.h"
#include "../Headers/log.h"
#include "FileSharing.h"
#include "fs.h"

using namespace TOB;

/* FS_Client */
FS_Client::FS_Client(std::string userName, std::string password, Nameserver::IP ip) : 
					 AuthRequired(userName, password, Nameserver::IP ip) {	
	ns = new Nameserver("localhost");
}
FS_Client::~FS_Client() {}

uint16 FS_Client::sendFile(std::string fileName) {
	if (0 != 0) { return Code::FS_SendFailure; } // auth
  if (file.open(fileName) != Code::Okay) { return Code::FS_SendFailure; }

	CLIENT* clnt;
  package p;
  uint8 buf[255];

	if (create_connection(clnt) != Code::Okay) { return Code::FS_SendFailure; }
  if (send_request(clnt, fileName) != Code::Okay) { return Code::FS_SendFailure; }; 
  while (FS_Client::getHandle(fileName)) {
    file.getBytes(fileName, 255, buf);
    make_package(buf, 255, &p);
    send_file_1(&p, clnt);
  }
  return Code::Okay;
}
/* Private methods */
uint16 create_connection(CLIENT* clnt) {
	Nameserver::IP ip;
	std::string address;

	if (ns->requestAddress(Server::FileSharing, &ip) != Code::Okay) {return Code::FS_FunctionCallFailure;}	
	if (ns->requestAddress(ip, address) != Code::Okay) {return Code::FS_FunctionCallFailure;}
	clnt = clnt_create(address.c_str(), FS_PROG, FS_VERSION, "tcp");  
	return Code::Okay;
}

uint16 send_request(CLIENT* clnt, std::string fileName) {
	message m;
	memcpy(m.username, userName.c_str(), userName.length());
	memcpy(m.name, fileName.c_str(), fileName.length());
	m.type = 0;
	request_1(&m, clnt);
	return Code::Okay;
}

uint16 make_package(uint8 * buf, int length, package& p) {
  memcpy(p.byte, buf, length);
  return Code::Okay;
}


int main(int argc, char ** argv) {
    	
		return 0;
}
